<template>
  <div class="top_content">
    <a-spin size="large" :spinning="spinning" tip="加载中">
      <div class="content">
        <div
          style="
            height: 40px;
            display: flex;
            margin-left: 24px;
            align-items: center;
            margin-bottom: 20px;
          "
        >
          <h2 style="font-weight: bold; color: #000000">等待买家付款：</h2>
          <div style="display: flex">
            <h2>剩</h2>
            <a-statistic-countdown
              :value="getDeadLine(deadline)"
              format="mm:ss"
            />
            <h2>分订单将自动取消</h2>
          </div>
        </div>
        <h2 class="header_title">
          选择收货地址
          <a-tag
            v-if="isAddAddress"
            @click="showModal"
            class="update_tag"
            style="font-size: 12px; height: 25px"
            color="#67C23A"
            >添加</a-tag
          >
        </h2>
        <div style="margin-top: 20px">
          <!-- 收获地址展示 -->
          <a-list :grid="{ column: 5 }" :data-source="address">
            <template #renderItem="{ item }">
              <a>
                <a-tooltip color="volcano">
                  <template #title>
                    <span
                      v-text="item.status === 1 ? '默认选择' : '点击选择'"
                    ></span>
                  </template>
                  <a-list-item @click="addressChecked(item.id)">
                    <div class="address_style" id="div_id">
                      <div style="height: 120px; padding: 10px">
                        <a-space class="toUser" :size="20">
                          <div style="width: 160px">
                            <span
                              style="overflow: hidden; text-overflow: ellipsis"
                              >{{ item.receiver }}收</span
                            >
                          </div>
                          <a-tag
                            v-if="item.status === 1 ? true : false"
                            style="font-size: 10px"
                            color="red"
                            >默认</a-tag
                          >
                        </a-space>
                        <div class="toAddressStyle">
                          <div
                            style="
                              overflow: hidden;
                              white-space: nowrap;
                              text-overflow: ellipsis;
                            "
                          >
                            {{ item.regionDetails }}
                          </div>
                          <div>{{ item.phone }}</div>
                          <a-space :size="20">
                            <div style="width: 157px"></div>
                            <a-tag v-if="item.selected" color="success"
                              ><template #icon>
                                <CheckOutlined
                                  style="padding-left: 5px"
                                /> </template
                            ></a-tag>
                          </a-space>
                        </div>
                      </div>
                    </div>
                  </a-list-item>
                </a-tooltip>
              </a>
            </template>
          </a-list>

          <!-- 商品信息展示 -->
          <div class="goodsInfo">
            <a-list item-layout="vertical" size="large" :data-source="listData">
              <!-- 页脚展示 -->
              <template #footer>
                <div
                  style="
                    margin-top: 20px;
                    margin-bottom: 80px;
                    display: flex;
                    justify-content: space-between;
                  "
                >
                  <!-- 左侧区域 -->
                  <div style="margin-left: 20px">
                    <h3>商品总价</h3>
                    <h3>订单编号</h3>
                    <h3>订单状态</h3>
                    <h3>订单创建</h3>
                  </div>

                  <!-- 右侧区域 -->
                  <div>
                    <div style="margin-bottom: 10px; font-weight: bold">
                      <span
                        ><PayCircleOutlined
                          style="margin-right: 5px; color: #ff0036"
                        />
                        <span
                          style="
                            font-size: 18px;
                            font-weight: bold;
                            color: #ff0036;
                          "
                        >
                          {{ towNumber(totalPrice) }}
                        </span>
                      </span>
                    </div>

                    <div style="margin-bottom: 10px">
                      <span style="font-size: 16px; font-weight: bold">{{
                        orderId
                      }}</span>
                    </div>

                    <div style="margin-bottom: 10px">
                      <span>
                        <a-tag
                          class="update_tag"
                          style="
                            font-weight: bold;
                            font-size: 14px;
                            height: 25px;
                            color: #303133;
                          "
                          color="#67C23A"
                          >{{ orderStatus }}</a-tag
                        >
                      </span>
                    </div>

                    <div>
                      <h3>{{ createTime }}</h3>
                    </div>
                  </div>
                </div>
              </template>
              <template #renderItem="{ item }">
                <a-list-item key="item.title">
                  <!-- 小图标展示 -->
                  <template #actions>
                    <span>
                      <component
                        :is="PayCircleOutlined"
                        style="margin-right: 8px; color: #ff0036"
                      />
                      单价：<span
                        style="
                          font-size: 16px;
                          font-weight: bold;
                          color: #ff0036;
                        "
                        >{{ towNumber(item.price) }}</span
                      >
                    </span>
                    <span>
                      <component
                        :is="DiffOutlined"
                        style="margin-right: 8px; color: #67c23a"
                      />
                      数量：<span
                        style="font-size: 16px; font-weight: bold; color: black"
                        >{{ item.number }}</span
                      >
                    </span>
                    <span>
                      <component
                        :is="AccountBookOutlined"
                        style="margin-right: 8px; color: #ff0036"
                      />
                      小计：<span
                        style="
                          font-weight: bold;
                          font-size: 16px;
                          color: #ff0036;
                        "
                        >{{ towNumber(item.subTotalPrice) }}</span
                      >
                    </span>
                  </template>
                  <!-- 最右侧图片 -->
                  <template #extra>
                    <img
                      width="100"
                      alt="logo"
                      :src="item.image"
                      style="border-radius: 10px"
                    />
                  </template>
                  <a-list-item-meta :description="item.introduce">
                    <template #title>
                      <router-link to="" @click="toShop(item.storeId)">
                        <h3 style="font-weight: bold">
                          {{ item.homeName }}
                        </h3>
                      </router-link>
                    </template>
                    <template #avatar
                      ><a-avatar size="large" :src="item.storeImage"
                    /></template>
                  </a-list-item-meta>
                  <router-link @click="toDetail(item.key)" to="">
                    <span style="font-weight: bold; font-size: 16px">
                      {{ item.name }}
                    </span>
                  </router-link>
                </a-list-item>
              </template>
            </a-list>
          </div>

          <!-- 提交订单按钮 -->
          <div>
            <a-affix :offset-bottom="bottom">
              <div class="commitOrder">
                <div style="display: flex">
                  <div style="margin-right: 10px; margin-top: 16px">
                    <span style="font-weight: bold">合计：</span>
                  </div>
                  <div style="margin-right: 5px; margin-top: 13px">
                    <span>
                      <PayCircleOutlined :style="iconStyle" />
                    </span>
                  </div>
                  <div style="margin-right: 20px; margin-top: 8px">
                    <span style="font: 700 26px tahoma; color: #ff0036">{{
                      towNumber(totalPrice)
                    }}</span>
                  </div>
                </div>
                <button
                  :disabled="isSuccessSubmit"
                  class="submit_order btn"
                  @click="submitOrder"
                >
                  {{ submitText }}
                </button>
              </div>
            </a-affix>
          </div>
        </div>
      </div>
    </a-spin>
  </div>

  <!-- 添加用户收获地址模态框 -->
  <div>
    <a-modal
      v-model:open="open"
      @cancel="handleCancel"
      title="添加收获地址"
      :footer="null"
    >
      <div style="padding: 30px 0 20px 50px">
        <a-form
          ref="formRef"
          :model="Address"
          :rules="rules"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-item ref="receiver" label="收货人" name="receiver">
            <a-input
              size="large"
              v-model:value="Address.receiver"
            /> </a-form-item
          ><a-form-item ref="phone" label="手机号" name="phone">
            <a-input size="large" v-model:value="Address.phone" />
          </a-form-item>
          <a-form-item label="验证码" ref="code" name="code">
            <a-input-search
              v-model:value="Address.code"
              placeholder="请输入验证码"
              @search="onSearch"
              style="width: 100%"
              maxlength="6"
              minlength="6"
              size="large"
            >
              <template #enterButton>
                <a-button
                  @click="getCode"
                  :disabled="disabled"
                  style="
                    background-color: #409eff;
                    color: #fff;
                    font-size: 10px;
                  "
                  >{{ content }}</a-button
                >
              </template>
            </a-input-search>
          </a-form-item>
          <a-form-item ref="regions" label="所在地区" name="regions">
            <a-cascader
              size="large"
              v-model:value="Address.regions"
              :options="options"
              placeholder="请选择地区"
              expand-trigger="hover"
            />
          </a-form-item>
          <a-form-item ref="detail" label="详细地址" name="detail">
            <a-textarea size="large" v-model:value="Address.detail" />
          </a-form-item>
          <a-form-item ref="status" label="默认地址" name="status">
            <a-switch v-model:checked="Address.checked" />
          </a-form-item>
          <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
            <a-button type="primary" @click="saveAddress">保存</a-button>
            <a-button style="margin-left: 10px" @click="handleCancel"
              >取消</a-button
            >
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </div>

  <!-- 支付二维码展示 -->
  <div>
    <a-modal
      v-model:open="modalPay"
      :closable="false"
      :footer="null"
      :maskClosable="false"
      centered
    >
      <div style="display: flex; justify-content: center; margin-bottom: 20px">
        <router-link to="" @click="changeAlipay">
          <a-radio :disabled="redioDisabled" v-model:checked="aliSeclectPay">
            <svg
              t="1704273620953"
              class="icon"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="1399"
              width="50"
              height="50"
            >
              <path
                d="M1024.0512 701.0304V196.864A196.9664 196.9664 0 0 0 827.136 0H196.864A196.9664 196.9664 0 0 0 0 196.864v630.272A196.9152 196.9152 0 0 0 196.864 1024h630.272a197.12 197.12 0 0 0 193.8432-162.0992c-52.224-22.6304-278.528-120.32-396.4416-176.64-89.7024 108.6976-183.7056 173.9264-325.3248 173.9264s-236.1856-87.2448-224.8192-194.048c7.4752-70.0416 55.552-184.576 264.2944-164.9664 110.08 10.3424 160.4096 30.8736 250.1632 60.5184 23.1936-42.5984 42.496-89.4464 57.1392-139.264H248.064v-39.424h196.9152V311.1424H204.8V267.776h240.128V165.632s2.1504-15.9744 19.8144-15.9744h98.4576V267.776h256v43.4176h-256V381.952h208.8448a805.9904 805.9904 0 0 1-84.8384 212.6848c60.672 22.016 336.7936 106.3936 336.7936 106.3936zM283.5456 791.6032c-149.6576 0-173.312-94.464-165.376-133.9392 7.8336-39.3216 51.2-90.624 134.4-90.624 95.5904 0 181.248 24.4736 284.0576 74.5472-72.192 94.0032-160.9216 150.016-253.0816 150.016z"
                fill="#009FE8"
                p-id="1400"
              ></path>
            </svg>
          </a-radio>
        </router-link>
      </div>
      <div v-if="isShow" style="display: flex; justify-content: center">
        <a-image
          :width="180"
          :height="180"
          :preview="false"
          :src="payUrl"
        ></a-image>
      </div>
      <div v-if="isShow" style="display: flex; justify-content: center">
        <h3 style="color: red; margin-top: 20px; margin-left: 5px">
          请在2分钟内完成支付！！
        </h3>
      </div>
      <div v-if="isShow" style="display: flex; justify-content: center">
        <a-spin :spinning="queryOrderSpinning" tip="支付订单查询中，请稍候~" />
      </div>
    </a-modal>
  </div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import {
  DiffOutlined,
  AccountBookOutlined,
  CheckOutlined,
  PayCircleOutlined,
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import router from "@/router";
import { useRoute } from "vue-router";
import { list, save, getAreaData } from "@/api/address";
import { getCartOrderList } from "@/api/cart";
import { saveOrder } from "@/api/order";
import { useUserStore } from "@/stores/user";
import { useAuthorizationStore } from "@/stores/authorization";
import { sendMs } from "@/api/sendMs";
import { getOrderCreateTime } from "@/api/pay.js";
import { queryOder, commonPay } from "@/api/reallpay.js";

const wxSeclectPay = ref(false);
const aliSeclectPay = ref(false);
const authorizationStore = useAuthorizationStore();
const route = useRoute();
const cartIds = ref([]);
cartIds.value = route.query.id;
const orderId = ref(null);
orderId.value = route.query.orderId;

const isAddAddress = ref(false);
const address = ref([]);
const listData = ref([]);
const totalPrice = ref(0);
const userStore = useUserStore();
const spinning = ref(true);
const createTime = ref(null);
const deadline = ref(null);
function getDeadLine(timeSecond) {
  let deadline = Date.now() + timeSecond * 1000;
  return deadline;
}
onMounted(() => {
  setTimeout(() => {
    getAllAreaData();
    //获取当前用户的所有收获地址
    getAddressList();
    ////获取购物车中的商品信息
    getCartOrderList(cartIds.value).then((res) => {
      if (res.code == 200) {
        listData.value = res.data.data;
        totalPrice.value = res.data.totalPrice;
      }
    });

    //获取订单创建时间
    getOrderCreateTime(orderId.value).then((res) => {
      if (res.code === 200) {
        createTime.value = res.data.createTime;
        if (res.data.timestamp !== null) {
          deadline.value = res.data.timestamp;
        } else {
          router.push("/personal");
          message.error("订单已超时，请重新下单哦！");
        }
      }
    });
    spinning.value = false;
  }, 1000);
});

const options = ref([]);
//获取省市区数据
function getAllAreaData() {
  getAreaData().then((res) => {
    if (res.code === 200) {
      options.value = res.data;
    }
  });
}

//订单所有数据封装
const orderDto = ref({
  userId: null,
  addressId: null,
  totalPrice: null,
  cartId: [],
  goodsId: null,
});

//提交订单方法
const redioDisabled = ref(false);
const isShow = ref(false);
const modalPay = ref(false);
const payUrl = ref("");
const tradeNo = ref("");
const orderStatus = ref("待支付");
const submitText = ref("立即支付");
const orderInfoVo = ref({});
const isSuccessSubmit = ref(false);
const queryOrderSpinning = ref(true);
const pay = ref({
  money: null,
  name: "",
  orderId: null,
  paymentType: "",
});
//支付接口
function submitOrder() {
  if (addressId.value === null) {
    message.error("请选择收货地址哦！");
  } else {
    //封装数据
    pay.value.money = totalPrice.value;
    pay.value.name = "曲师商城商品";
    pay.value.orderId = orderId.value;
    //封装数据
    orderDto.value.userId = userStore.user.key;
    orderDto.value.addressId = addressId.value;
    orderDto.value.totalPrice = totalPrice.value;
    cartIds.value.forEach(function (id) {
      orderDto.value.cartId.push(id);
    });
    modalPay.value = true;
  }
}

//支付宝支付
function changeAlipay() {
  wxSeclectPay.value = false;
  aliSeclectPay.value = true;
  redioDisabled.value = true;
  pay.value.paymentType = "alipay";
  //真实发送支付请求
  commonPay(pay.value).then((res) => {
    if (res.code === 200) {
      isShow.value = true;
      payUrl.value = res.data.payUrl;
      tradeNo.value = res.data.tradeNo;
      //定时5秒查询订单是否已经支付
      const setIntervalQuery = setInterval(() => {
        queryOder(tradeNo.value).then((res) => {
          if ((res.code === 200) && (res.data === true)) {
            //支付成功后停止定时轮询
            clearInterval(setIntervalQuery);
            message.success("支付成功！待商家发货咯");
            orderStatus.value = "已支付";
            submitText.value = "已支付";
            isSuccessSubmit.value = true;
            //异步去保存订单的详细信息
            saveOrder(orderDto.value, orderId.value, userStore.user.key).then(
              (res) => {
                if (res.code === 200) {
                  orderInfoVo.value = res.data;
                  router.push({ path: "/myGoods" });
                }
              }
            );
          }
        });
      }, 5000);
    }
  });
  //模拟发送支付请求,这个请求用于学习环境
  // commonPay(pay.value);
  //保存订单的详细信息
  // saveOrder(orderDto.value, orderId.value, userStore.user.key).then((res) => {
  //   if (res.code === 200) {
  //     message.success("支付成功！");
  //     orderInfoVo.value = res.data;
  //     router.push({ path: "/myGoods" });
  //   }
  // });
}

//这是底部提交订单按钮距离顶部的距离
const bottom = ref(20);

function getAddressList() {
  list(userStore.user.key).then((res) => {
    if (res.code == 200) {
      if (res.data === null || res.data.length === 0) {
        message.warning("您还没有添加收货地址哦！");
        isAddAddress.value = true;
      } else {
        address.value = res.data;
        isAddAddress.value = false;
      }
    }
  });
}

//展示价格的小数方法
function towNumber(val) {
  return val.toFixed(2);
}

//添加地址
const Address = ref({
  id: null,
  userId: null,
  receiver: "",
  phone: "",
  detail: "",
  regions: [],
  region: "",
  checked: false,
  status: 0,
  code: "",
});
const open = ref(false);
const showModal = () => {
  if (!authorizationStore.authorization) {
    message.error("需要先登录哦！");
  } else {
    open.value = true;
  }
};
//取消新增方法
function handleCancel() {
  address.value = {
    id: null,
    userId: null,
    receiver: "",
    phone: "",
    detail: "",
    region: "",
    checked: false,
    status: 0,
  };
  open.value = false;
}

//新增地址方法
function saveAddress() {
  formRef.value
    .validate()
    .then(() => {
      for (var i = 0; i < Address.value.regions.length; i++) {
        Address.value.region += Address.value.regions[i];
      }
      if (Address.value.checked) {
        Address.value.status = 1;
      } else {
        Address.value.status = 0;
      }
      Address.value.userId = userStore.user.key;
      save(Address.value).then((res) => {
        if (res.code == 200) {
          message.success("收获地址添加成功啦！");
          getAddressList();
          open.value = false;
          Address.value = {
            id: null,
            userId: null,
            receiver: "",
            phone: "",
            detail: "",
            region: "",
            checked: false,
            status: 0,
          };
        }
      });
    })
    .catch((error) => {
      console.log("error", error);
    });
}
const labelCol = {
  span: 5,
};
const wrapperCol = {
  span: 13,
};
const formRef = ref();
const rules = {
  regions: [
    {
      required: true,
      message: "请输入所在地区",
      trigger: "change",
    },
  ],
  code: [
    {
      required: true,
      message: "请输入手机验证码",
      trigger: "change",
    },
  ],
  receiver: [
    {
      required: true,
      message: "请设置收获人",
      trigger: "change",
    },
  ],
  detail: [
    {
      required: true,
      message: "请输入详细地址",
      trigger: "change",
    },
  ],
  phone: [
    {
      required: true,
      message: "请输入手机号",
      trigger: "change",
    },
    {
      min: 11,
      max: 11,
      message: "长度为11个字符",
      trigger: "blur",
    },
  ],
};

//获取验证码前确认是否是真实手机号
const disabled = ref(false);
const content = ref("获取验证码");
function getCode() {
  //请求发送短信
  if (Address.value.phone !== "") {
    sendMs(Address.value.phone).then((res) => {
      if (res.code === 200) {
        message.success("发送成功!");
      }
    });
    var time = 180;
    //禁用获取验证码按钮
    disabled.value = true;
    // 开启定时器
    var timer = setInterval(function () {
      // 判断剩余秒数
      if (time == 0) {
        // 清除定时器和复原按钮
        clearInterval(timer);
        disabled.value = false;
        content.value = "获取验证码";
      } else {
        content.value = `${time}秒后重新获取`;
        time--;
      }
    }, 1000);
  } else {
    message.error("请输入手机号");
  }
}

//去商品详情页
function toDetail(id) {
  router.push({ name: "Detail", query: { id: id } });
}

//选择收获地址
const addressId = ref(null);
function addressChecked(id) {
  address.value.map((item) => {
    if (item.id === id) {
      item.selected = true;
      addressId.value = id;
    } else {
      item.selected = false;
    }
  });
}

function toShop(id) {
  router.push({
    name: "Shop",
    query: {
      id: id,
    },
  });
}

//图标样式
const iconStyle = {
  fontSize: "25px",
  color: "#ff0036",
};
</script>

<style scoped>
a:hover {
  color: red;
}
.top_content {
  height: auto;
  margin-top: 10px;
  background-color: #fff;
}
.content {
  margin-left: 60px;
  margin-right: 60px;
  padding-top: 10px;
}

.header_title {
  line-height: 25px;
  color: #333;
  font-weight: 700;
  font-size: 14px;
  padding-left: 25px;
}

.address_style:hover {
  box-shadow: 10px 10px 5px gray, 10px 10px 5px gray;
}

.address_style {
  height: 120px;
  background-color: #fff;
  width: 230px;
  opacity: 0.8;
  transition: all 0.5s;
  border-radius: 10px;
}

.toUser {
  width: 100%;
  border-bottom: 1px solid #f2f2f2;
  padding: 0 0 5px;
  margin-bottom: 5px;
  line-height: 18px;
  font-weight: 700;
}

.toAddressStyle {
  letter-spacing: 1px;
  font-size: 12px;
  width: 220px;
  height: 80px;
}

.commitOrder {
  border-radius: 50px;
  display: flex;
  justify-content: flex-end;
  height: 50px;
  margin-left: 60px;
  margin-right: 60px;
  background: linear-gradient(90deg, rgb(255, 203, 0), rgb(255, 148, 2));
}

.submit_order {
  background: linear-gradient(90deg, rgb(255, 119, 0), rgb(255, 73, 0));
  border: none;
  height: 50px;
  width: 150px;
  color: #fff;
  font-weight: bold;
  font-size: 16px;
  border-radius: 50px;
}

.btn {
  transform: scale(1);
}

.btn:active {
  transform: scale(0.97);
}

.update_tag {
  transform: scale(1);
}

.update_tag:active {
  transform: scale(0.8);
}

.everyOne {
  margin-top: 20px;
  padding-left: 10px;
}

.order_item {
  font-size: 16px;
  font-weight: bold;
}

h3 {
  font-weight: bold;
}
/* :where(.css-dev-only-do-not-override-b92jn9).ant-statistic */
:deep(.ant-statistic) {
  line-height: 1;
}
</style>
